<script lang="ts" setup>
import { trimBlank } from '@vc/utils';
import { genFileId } from 'element-plus';
import message from 'vc/src/common/message';
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { useUserStore } from '../../../store/modules/user';
import { changeAvatar, submitUserAuthentication, uploadAuth, userEdit } from '../apis/profile';
import { noEmpty } from '../config';

interface Props {
  showDialog: boolean;
  isEdit: boolean;
}

const {
  showDialog,
  isEdit
} = defineProps<Props>();

const emit = defineEmits(['update:showDialog']);

const ruleFormRef = ref<FormInstance>();

const userStore = useUserStore();

const ruleForm = reactive({
  realName: userStore.getUserInfo.realName,
  businessCardFileId: '',
  companyAddress: userStore.getUserInfo.companyAddress,
  job: userStore.getUserInfo.job,
  industry: userStore.getUserInfo.industry,
  company: userStore.getUserInfo.company
});

let isChange = $ref(false);

const upload = ref();
let uploadFile = $ref('');

watch([()=> ruleForm, () => uploadFile], () => {
  isChange = true;
}, {
  deep: true
});

const handleExceed = (files) => {
  upload.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const { data, run } = useRequest(uploadAuth, {
  manual: true
});

const { run: reqChange, loading } = useRequest(submitUserAuthentication, {
  manual: true
});

const handleChange = (_uploadFile) => {
  const isJpgOrPng = _uploadFile.raw.type === 'image/jpg' || _uploadFile.raw.type === 'image/jpeg' || _uploadFile.raw.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('支持的文件格式为：jpg/jpeg/png');
    upload.value!.clearFiles();
    uploadFile = '';
    return false;
  } else if (_uploadFile.raw.size / 1024 / 1024 > 1) {
    message.error('图片大小不能超过 1 MB!');
    upload.value!.clearFiles();
    uploadFile = '';
    return false;
  } else {
    uploadFile = _uploadFile.raw;
  }
};

const handleSubmit = async () => {
  await ruleFormRef.value!.validate(async(valid) => {
    if (valid) {
      if (isChange) {
        if (!userStore.getUserInfo.businessCardUrl) {
          if (uploadFile) {
            run(uploadFile).then(() => {
              ruleForm.businessCardFileId = data.value?.[0]?.uuid;
              if (ruleForm.businessCardFileId) {
                handleSubmitFn();
              }
            });
          } else {
            message.error('请上传名片');
          }
        } else {
          if (uploadFile) {
            run(uploadFile).then(() => {
              ruleForm.businessCardFileId = data.value?.[0]?.uuid;
              if (ruleForm.businessCardFileId) {
                handleSubmitFn();
              }
            });
          } else {
            handleSubmitFn();
          }
        }
      } else {
        close();
      }
    }
  });
};

const handleSubmitFn = () => {
  reqChange(ruleForm).then((res) => {
    if (res.code === 200) {
      message.success('修改成功');
      userStore.getUserInfoAction();
      close();
    } else {
      message.error(res.msg);
    }
  });
};

function close () {
  emit('update:showDialog', false);
}
</script>

<template>
  <vc-dialog :title="isEdit ? '修改认证信息' : '填写认证信息'" :modelValue="showDialog"
    @close="close()"
    :height="600" :width="680">
    <div class="content">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        label-position="left"
        label-width="104px"
        @keypress.enter="handleSubmit"
      >
        <el-form-item label="上传名片" prop="businessCardFileId">
          <img v-if="!uploadFile && userStore.getUserInfo.businessCardUrl" class="mr-8px border border-[#dcdfe6] w-146px h-146px"
            :src="userStore.getUserInfo.businessCardUrl" alt="" />
          <el-upload ref="upload" list-type="picture-card"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :auto-upload="false"
            :limit="1"
          >
            <vc-icon icon="vi-add" />
            <template #file="{ file }">
              <div class="w-full text-center">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item :rules="[noEmpty('')]" label="真实姓名" prop="realName">
          <el-input maxlength="10" class="input" placeholder="请输入真实姓名" v-model="ruleForm.realName" />
        </el-form-item>
        <el-form-item :rules="[noEmpty('')]" label="企业名称" prop="company">
          <el-input maxlength="50" class="input" placeholder="请输入您所在的企业名称" v-model="ruleForm.company" />
        </el-form-item>
        <el-form-item :rules="[noEmpty('')]" label="行业名称" prop="industry">
          <el-input maxlength="50" class="input" placeholder="请输入您所在的行业名称"
            v-model="ruleForm.industry" />
        </el-form-item>
        <el-form-item :rules="[noEmpty('')]" label="职务名称" prop="job">
          <el-input maxlength="20" class="input" placeholder="请输入您的职务名称" v-model="ruleForm.job" />
        </el-form-item>
        <el-form-item :rules="[noEmpty('')]" label="公司地址" prop="companyAddress">
          <el-input maxlength="100" class="input" placeholder="请输入公司详细地址"
            v-model="ruleForm.companyAddress" />
        </el-form-item>
        <el-form-item class="fr">
          <el-button class="change-color" @click="emit('update:showDialog', false)">取消</el-button>
          <el-button :loading="loading" type="primary" color="#02C680" style="color:#FFFFFF;" @click="handleSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </vc-dialog>
</template>

<style lang="scss" scoped>
.content {
  padding: 24px;
}

:deep(.content) {
  .el-form-item__label {
    margin-top: 4px;
    &::before {
    	content: '';
    	display: none;
    }
  }
  .el-input__wrapper.is-focus{
    box-shadow: 0 0 0 1px #02C680 inset;
  }
  .el-upload--picture-card:hover,.el-upload:focus{
    color: #02C680;
    border-color: #02C680;
  }
}
:deep(.change-color){
  &:hover{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
  &:focus{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
}
</style>
